﻿using System;
using System.Collections;
using System.Configuration;
using System.Drawing;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
using com.kmxy.MonitorManager.Properties;
using com.kmxy.MonitorModel;

namespace com.kmxy.MonitorManager
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
        }
        private WinServiceManager _serverManager;
        private string _mTitle = "服务控制台 V1.x";
        private string _serviceName = "kmxyOfDaemonMonitorServer";
        private string _serviceExeName = "MonitorServer.exe";
        private string _servicePath = AppDomain.CurrentDomain.BaseDirectory;
        private delegate void DSetLabelText(string txt);
        private delegate void DSetBtnEnabled(bool state);
        private delegate void DSetCursorState(Cursor c);
        private delegate void DSetRunColor(Color color);
        private bool _run = false;
        private void MainFrm_Load(object sender, EventArgs e)
        {
            if (!IsAdministrator()) { MessageBox.Show(Resources.MainFrm_RunAsAdmin, Resources.Frm_MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); Application.Exit(); }
            t_ServiceCheck.Enabled = true;
            Start();
            _run = true;
            var name = ConfigurationManager.AppSettings["ServiceName"];
            var exeName = ConfigurationManager.AppSettings["ServiceExeName"];
            var path = ConfigurationManager.AppSettings["ServicePath"];
            var appTitle = ConfigurationManager.AppSettings["AppTitle"];
            if (!string.IsNullOrEmpty(name)) _serviceName = name.Trim();
            if (!string.IsNullOrEmpty(exeName)) _serviceExeName = exeName.Trim();
            if (!string.IsNullOrEmpty(path)) _servicePath = path.Trim();
            if (!string.IsNullOrEmpty(appTitle)) _mTitle = appTitle;
            Text = _mTitle;

        }
        public static bool IsAdministrator()
        {
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        private void SetCurrentCursorState(Cursor c)
        {
            if (InvokeRequired)
            {
                DSetCursorState ds = SetCurrentCursorState;
                Invoke(ds, c);
            }
            else
            {
                Cursor = c;
            }
        }
        private void SetServiceState(string txt)
        {
            if (lbl_SerState.InvokeRequired)
            {
                DSetLabelText ds = SetServiceState;
                lbl_SerState.Invoke(ds, txt);
            }
            else
            {
                lbl_SerState.Text = txt;
                lbl_SerState.ForeColor = txt == "服务已存在" ? Color.Green : Color.Red;
            }
        }
        private void SetInstallState(bool state)
        {
            if (btn_SerSetup.InvokeRequired)
            {
                DSetBtnEnabled ds = SetInstallState;
                btn_SerSetup.Invoke(ds, state);
            }
            else
            {
                btn_SerSetup.Enabled = state;
            }
        }
        private void SetUnInstallState(bool state)
        {
            if (btn_SerSetup.InvokeRequired)
            {
                DSetBtnEnabled ds = SetUnInstallState;
                btn_SerSetup.Invoke(ds, state);
            }
            else
            {
                btn_SerUnSetup.Enabled = state;
            }
        }
        private void SetRunState(bool state)
        {
            if (btn_SerSetup.InvokeRequired)
            {
                DSetBtnEnabled ds = SetRunState;
                btn_SerSetup.Invoke(ds, state);
            }
            else
            {
                btn_Run.Enabled = state;
            }
        }
        private void SetStopState(bool state)
        {
            if (btn_SerSetup.InvokeRequired)
            {
                DSetBtnEnabled ds = SetStopState;
                btn_SerSetup.Invoke(ds, state);
            }
            else
            {
                btn_Stop.Enabled = state;
            }
        }
        private void SetReStartState(bool state)
        {
            if (btn_SerSetup.InvokeRequired)
            {
                DSetBtnEnabled ds = SetReStartState;
                btn_SerSetup.Invoke(ds, state);
            }
            else
            {
                btn_ReStart.Enabled = state;
            }
        }
        private void SetRunSteIsShow(bool ste)
        {
            if (lbl_ServiceRunState.InvokeRequired)
            {
                DSetBtnEnabled ds = SetRunSteIsShow;
                lbl_ServiceRunState.Invoke(ds, ste);
            }
            else
            {
                lbl_ServiceRunState.Visible = ste;
            }
        }
        private void SetRunColor(Color color)
        {

            if (lbl_SerSetup.InvokeRequired)
            {
                DSetRunColor c = SetRunColor;
                try
                {
                    lbl_SerSetup.Invoke(c, color);
                }
                catch (Exception)
                {

                }

            }
            else
            {
                lbl_SerSetup.ForeColor = color;
            }
        }
        private void SetSerStateColor(Color color)
        {
            if (lbl_SerState.InvokeRequired)
            {
                DSetRunColor c = SetSerStateColor;
                try
                {
                    lbl_SerState.Invoke(c, color);
                }
                catch (Exception)
                {

                }

            }
            else
            {
                lbl_SerState.ForeColor = color;
            }
        }
        private void SetRunSteColor(Color color)
        {

            if (lbl_ServiceRunState.InvokeRequired)
            {
                DSetRunColor c = SetRunSteColor;
                try
                {
                    lbl_ServiceRunState.Invoke(c, color);
                }
                catch (Exception)
                {

                }

            }
            else
            {
                lbl_ServiceRunState.ForeColor = color;
            }
        }
        private void SetSetupState()
        {
            var rand = new Random(DateTime.Now.Second);
            while (_run)
            {
                SetRunColor(Color.Blue);
                Thread.Sleep(rand.Next(200, 800));
                SetRunColor(Color.Red);
                Thread.Sleep(rand.Next(300, 700));
            }
        }
        private void SetRunSteState()
        {
            var rand = new Random(DateTime.Now.Second);
            SetRunSteColor(Color.Red);
            while (_run)
            {
                if (lbl_SerState.Text == "Running")
                {
                    SetRunSteColor(Color.Green);
                    Thread.Sleep(rand.Next(200, 800));
                    SetRunSteColor(Color.LightGreen);
                    Thread.Sleep(rand.Next(300, 700));
                }
                else
                {
                    SetRunSteColor(Color.Red);
                }
            }
        }

        private void Start()
        {
            _serverManager = new WinServiceManager(_serviceName);
            if (_serverManager.ServiceIsExisted(_serviceName))
            {
                SetServiceState("服务已存在");
                SetInstallState(false);
            }
            else
            {
                SetServiceState("服务不存在");
                SetUnInstallState(false);
            }
            new Thread(new ThreadStart(SetSetupState)).Start();
            new Thread(new ThreadStart(SetRunSteState)).Start();
        }

        private void btn_SerSetup_Click(object sender, EventArgs e)
        {
            new Thread(new ThreadStart(InStallService)).Start();
        }
        private void InStallService()
        {
            SetCurrentCursorState(Cursors.WaitCursor);
            if (_serverManager != null)
            {
                IDictionary mySavedState = new Hashtable();
                try
                {
                    _serverManager.InstallService(mySavedState, _servicePath, _serviceExeName);
                    SetServiceState("服务已存在");
                    SetInstallState(false);
                    SetUnInstallState(true);
                    MessageBox.Show("服务安装成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务安装失败！" + ex.Message, "服务安装失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetCurrentCursorState(Cursors.Default);
                }

            }
        }
        private void btn_SerUnSetup_Click(object sender, EventArgs e)
        {
            new Thread(new ThreadStart(UnInstallService)).Start();
        }
        private void UnInstallService()
        {
            SetCurrentCursorState(Cursors.WaitCursor);

            if (_serverManager != null)
            {
                IDictionary mySavedState = new Hashtable();
                try
                {
                    var exeSte = string.Empty;
                    ProcessUtility.KillProcess(_serviceExeName, out exeSte);
                    _serverManager.UnInstallService(_servicePath, _serviceExeName);
                    SetServiceState("服务不存在");
                    SetInstallState(true);
                    SetUnInstallState(false);
                    MessageBox.Show("服务卸载成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务卸载失败！" + ex.Message, "服务卸载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetCurrentCursorState(Cursors.Default);
                }

            }
        }
        private void SetStateBarTimeState(string txt)
        {
            if (statusStrip1.InvokeRequired)
            {
                DSetLabelText ds = SetStateBarTimeState;
                statusStrip1.Invoke(ds, txt);
            }
            else
            {
                lbl_Time.Text = txt;
            }
        }
        private void SetStateBarLableState(string txt)
        {
            if (statusStrip1.InvokeRequired)
            {
                DSetLabelText ds = SetStateBarLableState;
                statusStrip1.Invoke(ds, txt);
            }
            else
            {
                lbl_SevState.Text = txt;
            }
        }
        private void SetServiceName(string txt)
        {
            if (lbl_SerName.InvokeRequired)
            {
                DSetLabelText ds = SetServiceName;
                lbl_SerName.Invoke(ds, txt);
            }
            else
            {
                lbl_SerName.Text = txt;
            }
        }


        private void btn_Run_Click(object sender, EventArgs e)
        {
            SetCurrentCursorState(Cursors.WaitCursor);
            if (_serverManager != null)
            {
                try
                {
                    if (_serverManager.StartService(_serviceName))
                    {
                        MessageBox.Show("服务已启动！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("服务未成功启动！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务启动失败：" + ex.Message, _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetCurrentCursorState(Cursors.Default);
                }

            }
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            SetCurrentCursorState(Cursors.WaitCursor);
            if (_serverManager != null)
            {
                try
                {
                    if (_serverManager.StopService(_serviceName))
                    {
                        MessageBox.Show("服务已停止！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("服务未成功停止！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务停止失败：" + ex.Message, _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetCurrentCursorState(Cursors.Default);
                }

            }
        }

        private void btn_ReStart_Click(object sender, EventArgs e)
        {
            SetCurrentCursorState(Cursors.WaitCursor);
            if (_serverManager != null)
            {
                try
                {
                    if (_serverManager.StopService(_serviceName))
                        if (_serverManager.StartService(_serviceName))
                            MessageBox.Show("服务已启动！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        else
                            MessageBox.Show("服务未成功启动！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        MessageBox.Show("服务未成功停止！", _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务重启失败：" + ex.Message, _mTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetCurrentCursorState(Cursors.Default);
                }

            }
        }

        private void t_ServiceCheck_Tick(object sender, EventArgs e)
        {

            SetStateBarTimeState(DateTime.Now.ToString());
            if (_serverManager != null)
            {
                var s = _serverManager.GetService(_serviceName);
                SetServiceName(_serviceName);
                SetStateBarLableState(s);
                SetServiceState(s);
                switch (s)
                {
                    case "Stopped":
                        {
                            SetRunState(true);
                            SetStopState(false);
                            SetReStartState(true);
                            SetUnInstallState(true);
                            SetSerStateColor(Color.Red);
                            //SetRunSteIsShow(false);
                        }
                        break;
                    case "Running":
                        {
                            SetRunState(false);
                            SetStopState(true);
                            SetReStartState(true);
                            SetUnInstallState(true);
                            SetSerStateColor(Color.Green);
                            //SetRunSteIsShow(true);
                        }
                        break;
                    case "NoExists":
                    case "Unknowd":
                        {
                            SetRunState(false);
                            SetStopState(false);
                            SetReStartState(false);
                            SetInstallState(true);
                            SetUnInstallState(false);
                            SetServiceState(s);
                            SetSerStateColor(Color.Red);
                            //SetRunSteIsShow(false);
                        }
                        break;
                }

            }
        }


        private void lbl_SerSetup_Click(object sender, EventArgs e)
        {
            if (lbl_SerSetup.Text == "<<<<")
            {
                lbl_SerSetup.Text = ">>>>";
                groupBox3.Visible = false;
                lbl_SerSetup.ForeColor = Color.Red;
            }
            else
            {
                groupBox3.Visible = true;
                lbl_SerSetup.Text = "<<<<";
                lbl_SerSetup.ForeColor = Color.Blue;
            }
        }

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _run = false;
            Application.ExitThread();
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            _run = false;
            Close();
            Thread.Sleep(300);
            Application.ExitThread();
            Application.Exit();
        }

       
    }
}
